/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.webbapps.cormac_susilo.resources;

import edu.webbapps.cormac_susilo.core.IUserModel;
import edu.webbapps.cormac_susilo.wrappers.RunWrapper;
import java.util.List;
import java.util.NoSuchElementException;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.RollbackException;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;

/**
 *
 * @author tor
 */
@RequestScoped
@Path("user/{user_id}/track")
public class TrackResource {

    @Inject
    private IUserModel mgr;
    @Context
    private UriInfo context;

    @GET
    @Produces("application/json")
    public Response getTrackByUser(
            @PathParam("user_id") long user_id) {

        try {
            List<String> tracks = mgr.getTracks(user_id);
            return Response.ok(tracks).build();
            
        } catch (NoSuchElementException e) {
            return Response.noContent().build();
        }
    }

    @GET
    @Path("{track_name}")
    @Produces("application/json")
    public Response getRunsByTrackAndUser(
            @PathParam("user_id") long user_id, @PathParam("track_name") String trackname) {

        try {
            List<RunWrapper> runs = mgr.getRuns(user_id, trackname);
            GenericEntity<List<RunWrapper>> ge = new GenericEntity<List<RunWrapper>>(runs) {};
            return Response.ok(ge).build();
            
        } catch (NoSuchElementException e) {
            return Response.noContent().build();
        }
    }

    @PUT
    @Path("{track_name}")
    @Produces("application/json")
    public Response update(
            @PathParam("user_id") long user_id, @PathParam("trackname") String trackname, @FormParam("new_trackname") String new_trackname) {

        if (new_trackname == null) {
            return Response.status(Status.BAD_REQUEST).build();
        }
        if (new_trackname.isEmpty() || new_trackname.length() > 32) {
            return Response.status(Status.NOT_ACCEPTABLE).build();
        }

        try {
            mgr.renameRuns(user_id, trackname, new_trackname);
            return Response.ok().build();
            
        } catch (RollbackException e) {
            return Response.serverError().build();
        } catch (NoSuchElementException e) {
            return Response.status(Status.NOT_FOUND).build();
        }
    }
}
